package com.blackhorse.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
//Gateway限流的配置
@Configuration
public class KeyResolverConfiguration {
    /**
     * 编写基于请求路径的限流规则
     * 某个路径每次被请求为从令牌桶取出令牌，当没有令牌时无法访问或等待，从而实现限流
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        //自定义的KeyResolver，参数ServerWebExchange， SpringCloudGateway的上下文参数
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getPath().toString());
            }
        };
    }

    /**
     * 编写基于请求参数的限流规则
     * 例如当某个路径携带了userId=1参数后，userId=1的频繁请求会被限流
     */
    //@Bean
    public KeyResolver userKeyResolver() {//使用lambda表达式的简化写法
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("userId"));
    }


    /**
     * 编写基于客户端IP的限流规则
     */
   // @Bean
    public KeyResolver clientIpResolver() {//使用lambda表达式的简化写法
        return exchange -> Mono.just(exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"));
    }

}
